import doWithMap from './map';

const doOther = (data, resolve, params) => {
  const app = getApp();
  const { silence, interceptor } = params;
  const { result = {} } = data;
  const { __toast } = result;

  if (__toast && !silence) {
    wx.nextTick(() => {
      wx.showToast({
        icon: 'none',
        title: __toast
      });
    });
  }

  doWithMap(result);

  if(typeof app.actionMap['apiCallback'] === 'function'){
    app.actionMap['apiCallback'](data);
    app.actionMap['apiCallback'] = null;
  }

  if(typeof interceptor === 'function') {
    data.result = interceptor(result) || result;
  }

  data.success = true;
  resolve(data);
};

const success = (data, resolve, params) => {
  const app = getApp();
  const { api, data:paramData, silence, ignore } = params;
  const { result = {}, error } = data;
  const { __message, __message_title = '提示', __message_cancel = false, __message_no_execute } = result;

  app.info('操作:调用' + api + '方法，', '参数:' + JSON.stringify(data || {}));
  console.log('api ' + api)

  if (__message) {

    if(!ignore){
      console.log(api + '方法：');
      console.log('参数：');
      console.log(JSON.stringify(paramData || {}));
      console.log('返回:');
      console.log(data);

      app.info('事件:' + api + '方法返回，', '参数:' + JSON.stringify(paramData || {}) + '，', '返回:' + JSON.stringify(data));
    }

    wx.showModal({
      title: __message_title,
      content: __message,
      showCancel: __message_cancel,
      success(res) {
        if(res.confirm){
          doOther(data, resolve, params); // 其他类型的操作
        }
      }
    });
  }
  else{
    if(!ignore){
      console.log(api + '方法：');
      console.log('参数：');
      console.log(JSON.stringify(paramData || {}));
      console.log('返回:');
      console.log(data);

      app.info('事件:' + api + '方法返回，', '参数:' + JSON.stringify(paramData || {}) + '，', '返回:' + JSON.stringify(data));
    }

    doOther(data, resolve, params); // 其他类型的操作
  }
};
module.exports = success;
